<script lang="ts">
  import { register, getCodeImg, getTelRegisterCodeApi } from '@/api';
  import { UpdateRegisterDto } from '@/api/model/index';
  import { ElForm, ElMessage } from 'element-plus';
  // import { ComponentInternalInstance } from 'vue';
  import $model from '@/plugins/modal';

  import { openLoginBox, openModelResetPwd, openModelRegister } from '@/pages/common/showModel';

  export default defineComponent({
    name: 'ModelRegister',
    setup() {
      // const Instance = getCurrentInstance() as ComponentInternalInstance;
      const state = reactive<any>({
        loading: false,
        activeTabName: 'pwd', //pwd | code
        codeUrl: '',
        open: false,

        rules: {
          nickName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          // 手机号
          phonenumber: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {
              pattern: /^1[3456789]\d{9}$/,
              message: '请输入正确的手机号',
              trigger: 'blur',
            },
          ],

          // 身份证
          idNo: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
            {
              pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
              message: '请输入正确的身份证号',
              trigger: 'blur',
            },
          ],
          // 请输入8-16位登录密码，必须包含（大小写字母、数字、特殊字符）
          password: [
            { required: true, message: '请输入登录密码', trigger: 'blur' },
            // <div>1、密码不可以包含3位相同或键盘中相邻连续字符，例:AAA、qaz都不符合要求。</div>
            // <div>2、密码不应包含年份。</div>
            // <div>3、密码至少包含数字、小写字母、大写字母、特殊字符，至少三种。</div>
            // <div>4、特殊字符包含:._~!@#$^&*</div>
            // {
            //   // /[.*~!@#$%^&*()_+|<>,.?/:.'\\[\\\]{}\"]/
            //   pattern:
            //     /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[.*~!@#$%^&*()_+|<>,.?/:;'\\[\\\]{}\"*])[A-Za-z\d.\-.*~!@#$%^&*()_+|<>,.?/:;'\\[\\\]{}\"*]{8,16}$/,
            //   message: '请输入8-16位登录密码，必须包含大小写字母、数字及特殊字符。',
            //   trigger: 'blur',
            // },
            {
              // pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,16}$/,
              pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,16}$/,
              trigger: 'blur',
              message: '请输入8-16位登录密码，必须包含大小写字母及数字',
            },
            // {
            //   pattern:
            //     /^(?!.*([a-zA-Z0-9])\1\1)(?!.*(?:qwerty|asdf|zxcvbn|123|qaz|123q|!@#$%^&*))[A-Za-z\d.\-_~!@#$^&*]{8,16}$/,
            //   message: '密码不可以包含3位相同或键盘中相邻连续字符，例:AAA、qaz都不符合要求。',
            //   trigger: 'blur',
            // },
            // {
            //   pattern: /^(?!.*\d{4})(?!.*\d{2}\d{2}).{8,16}$/,
            //   message: '密码不应包含年份',
            //   trigger: 'blur',
            // },
          ],

          // 确认密码
          passwordOk: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (value !== state.formData.password) {
                  callback(new Error('两次输入密码不一致!'));
                } else {
                  callback();
                }
              },
              trigger: 'blur',
            },
          ],
          smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
          code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        },
        formData: {},
      });
      const formRef = ref<InstanceType<typeof ElForm>>();
      //微信登录状态
      const wecahtQR = ref({
        url: '',
        show: false,
      });
      // 验证码开关
      const captchaEnabled = ref(true);
      const telMsg = ref('获取验证码');
      let interval: NodeJS.Timeout | null = null;
      const formData = ref<UpdateRegisterDto>(state.formData);
      const { loading, activeTabName, codeUrl, open, rules } = toRefs(state);

      // 获取短信验证码
      const getTelCode = () => {
        if (telMsg.value === '获取验证码') {
          if (formData.value.phonenumber) {
            // // 获取短信验证码
            getTelRegisterCodeApi(formData.value.phonenumber)
              .then((res) => {
                if (res.code === 200) {
                  let count = 60;
                  telMsg.value = `${count}s`;
                  interval = setInterval(() => {
                    count--;
                    telMsg.value = `${count}s`;
                    if (count === 0) {
                      clearInterval(interval as NodeJS.Timeout);
                      telMsg.value = '获取验证码';
                    }
                  }, 1000);
                }
              })
              .catch(() => {
                telMsg.value = '获取验证码';
              });
          } else {
            $model.msgError('请输入手机号');
          }
        }
      };

      onUnmounted(() => {
        clearInterval(interval as NodeJS.Timeout);
      });

      const onWecaht = () => {
        wecahtQR.value.show = !wecahtQR.value.show;
        console.log('onWecaht');
      };
      const openModel = () => {
        getCode();
        console.log(state, 'login');
        open.value = true;
      };

      const closeModel = () => {
        open.value = false;
      };

      function getCode() {
        getCodeImg().then(({ data: res }: any) => {
          captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
          if (captchaEnabled.value) {
            codeUrl.value = 'data:image/gif;base64,' + res.img;
            formData.value.uuid = res.uuid;
          }
        });
      }

      // const LoginRef = inject<any>('LoginRef');
      // const RegisterRef = inject<any>('RegisterRef');
      // const ResetPwdRef = inject<any>('ResetPwdRef');
      function openLogin() {
        // LoginRef.value.openModel();
        openLoginBox();
        open.value = false;
      }
      const openRegister = async () => {
        // RegisterRef.value.openModel();
        openModelRegister();
        open.value = false;
        await nextTick();
        formRef.value?.clearValidate();
      };
      function openResetPwd() {
        // ResetPwdRef.value.openModel();
        openModelResetPwd();
        open.value = false;
      }

      async function submit() {
        const valid = await formRef.value?.validate();
        if (valid) {
          console.log('submit');
          // formData.value.smsCode = 123424;
          register({ ...formData.value, userType: 1 })
            .then((res) => {
              console.log(res);
              if (res.code === 200) {
                ElMessage.success('注册成功');
                openLogin();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      }
      return {
        telMsg,
        formRef,
        submit,
        openLogin,
        openRegister,
        captchaEnabled,
        openResetPwd,
        onWecaht,
        wecahtQR,
        getCode,
        getTelCode,
        openModel,
        closeModel,
        loading,
        activeTabName,
        codeUrl,
        open,
        rules,
        formData,
      };
    },
  });
</script>
<template>
  <el-dialog
    class="register-popup"
    top="50px"
    v-model="open"
    v-if="open"
    center
    :show-close="false"
    width="788px"
    append-to-body
  >
    <ScreenAdapter elementDom=".register-popup">
      <div class="login">
        <div class="login-wechat">
          <div class="login-wechat__cover">
            <img src="@/assets/images/dashboard/wechat-main.png" alt="" />
          </div>
          <div class="login-wechat__title">扫一扫，登录小程序</div>
        </div>
        <el-form
          label-position="top"
          ref="formRef"
          hide-required-asterisk
          :model="formData"
          :rules="rules"
          class="login-form"
        >
          <div class="login-form__title">注册</div>
          <el-form-item prop="nickName" label="姓名">
            <el-input
              v-model="formData.nickName"
              type="text"
              auto-complete="off"
              placeholder="请输入姓名"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore" class="el-input__icon input-icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="phonenumber" label="手机号">
            <el-input
              v-model="formData.phonenumber"
              type="text"
              auto-complete="off"
              placeholder="请输入手机号"
              @keyup.enter="submit"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore" class="el-input__icon input-icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="idNo" label="身份证号">
            <el-input
              v-model="formData.idNo"
              type="text"
              auto-complete="off"
              placeholder="请输入身份证号"
              @keyup.enter="submit"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore" class="el-input__icon input-icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" label="登录密码">
            <el-input
              v-model="formData.password"
              type="password"
              show-password
              auto-complete="off"
              placeholder="请输入8-16位登录密码，必须包含大小写字母及数字"
              @keyup.enter="submit"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore-1" class="el-input__icon input-icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="passwordOk" label="确认密码">
            <el-input
              v-model="formData.passwordOk"
              type="password"
              show-password
              auto-complete="off"
              placeholder="请再次输入密码"
              @keyup.enter="submit"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore-1" class="el-input__icon input-icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="text-13px" label="图形验证码">
            <el-input
              v-model="formData.code"
              auto-complete="off"
              placeholder="请输入右侧图形验证码的算术结果"
              style="width: calc(63% - 20px)"
              @keyup.enter="submit"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore-2" class="el-input__icon input-icon" />
              </template>
            </el-input>
            <div class="login-code !w-[37%]">
              <img :src="codeUrl" @click="getCode" class="login-code-img !w-full !h-full" />
            </div>
          </el-form-item>

          <el-form-item v-if="captchaEnabled" prop="smsCode" label="短信验证码">
            <el-input
              v-model="formData.smsCode"
              @keyup.enter="submit"
              auto-complete="off"
              placeholder="请输入短信验证码"
              style="width: calc(63% - 20px)"
            >
              <template #prefix>
                <svg-icon icon-class="addBefore-2" class="el-input__icon input-icon" />
              </template>
            </el-input>
            <el-button
              plain
              type="primary"
              color="#165dff"
              @click="getTelCode"
              class="login-code !w-[37%] login-code-btn"
            >
              {{ telMsg || '获取验证码' }}
            </el-button>
          </el-form-item>
          <div style="width: 100%; margin-top: 20px">
            <el-button @click="submit" color="#165dff" class="submitClass" type="primary">
              <span v-if="!loading">立即注册</span>
              <span v-else>立即注册中...</span>
            </el-button>
            <div class="mt20px flex justify-end flex-items-center flex-content-center text-right">
              <div>
                已有账号？
                <el-button @click="openLogin" type="text">去登录 ></el-button>
              </div>
            </div>
          </div>
        </el-form>

        <div @click="closeModel" class="close-bottom">
          <img src="@/assets/images/dashboard/close-btn-footer.png" alt="" />
        </div>
      </div>
    </ScreenAdapter>
  </el-dialog>
</template>

<style lang="scss">
  .register-popup {
    position: relative;
    padding: 0;
    border-radius: 8px;

    .el-dialog__headerbtn .el-dialog__close {
      font-size: 20px;
    }

    .el-dialog__body {
      padding: 10px 20px 20px;
    }

    .login-form__title {
      height: 30px;
      margin: 10px auto 20px;
      color: #165dff;
      font-family: 'Alibaba PuHuiTi';
      font-size: 26px;
      font-style: normal;
      font-weight: normal;
      line-height: 30px;
      text-align: center;
      text-transform: none;
    }

    .wechat-QR {
      &-title {
        height: 30px;
        color: #165dff;
        font-family: 'Alibaba PuHuiTi';
        font-size: 26px;
        font-style: normal;
        font-weight: normal;
        line-height: 30px;
        text-align: center;
        text-transform: none;
      }

      &-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 97px;
        margin-bottom: 113px;

        &__if {
          width: 200px;
          height: 200px;
          padding: 20px;
          border: 1px solid #dadada;
          background: url('@/assets/images/dashboard/wechat-border.png') no-repeat;
          background-size: 100% 100%;

          img {
            width: 100%;
            height: 100%;
          }
        }

        &__tips {
          margin-top: 40px;

          .title {
            color: #333;
            font-family: 'Alibaba PuHuiTi';
            font-size: 20px;
            font-style: normal;
            font-weight: normal;
            line-height: 30px;
            text-align: center;
            text-transform: none;
          }

          .value {
            color: #666;
            font-family: 'Alibaba PuHuiTi';
            font-size: 16px;
            font-style: normal;
            font-weight: normal;
            line-height: 30px;
            text-align: center;
            text-transform: none;
          }
        }
      }
    }

    .el-tabs {
      position: relative;

      .el-tabs__nav-wrap::after {
        display: none;
      }

      .el-tabs__active-bar {
        display: none;
      }

      .el-tabs__item {
        color: #666;
        font-family: 'Alibaba PuHuiTi';
        font-size: 18px;
        font-style: normal;
        font-weight: normal;
        line-height: 30px;
        text-align: center;
        text-transform: none;
      }

      .is-active {
        color: #165dff;
        font-family: 'Alibaba PuHuiTi';
        font-size: 26px !important;
        font-style: normal;
        font-weight: normal;
        line-height: 30px;
        text-align: center;
        text-transform: none;
      }
    }

    .el-tab-pane {
      margin-top: 36px;
    }

    .login {
      display: flex;
      box-sizing: border-box;
      align-items: center;
      justify-content: space-between;
      //position: relative;
    }

    .close-bottom {
      position: absolute;
      z-index: 10;
      bottom: -80px;
      left: 50%;
      height: 80px;
      transform: translateX(-50%);

      img {
        width: 34px;
        height: 80px;
        cursor: pointer;
      }
    }

    .login-code-btn {
      --el-button-border-color: #165dff !important;
      --el-button-bg-color: transparent !important;
      --el-button-hover-bg-color: transparent !important;
      --el-button-hover-text-color: #165dff !important;
      --el-button-text-color: #165dff !important;
    }

    .login-code {
      height: 44px;
    }

    .login-wechat {
      display: flex;
      flex: 1;
      flex-direction: column;
      align-content: center;
      align-items: center;
      padding-top: 30px;

      &__title {
        margin-top: 20px;
        color: #333;
        font-family: 'Alimama ShuHeiTi', serif;
        font-size: 20px;
        line-height: 48px;
        text-align: center;
      }

      &__cover {
        width: 200px;
        height: 200px;
        padding: 4px;
        //border: 1px solid #dadada;
        //
        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .login-form {
      position: relative;
      flex: 0 0 456px;
      width: 456px;
      padding: 0 10px 0 32px;
      background: #fff;

      &::after {
        content: ' ';
        position: absolute;
        top: 50%;
        left: 0;
        width: 1px;
        height: 80%;
        transform: translateY(-50%);
        background: #f2f3f5;
      }
      //.el-input {
      //  height: 40px;
      //  input {
      //    height: 40px;
      //  }
      //}

      .login-tip {
        color: #bfbfbf;
        font-size: 13px;
        text-align: center;
      }

      .footFlex {
        display: flex;
        justify-content: space-between;
        margin-top: 12px;
        margin-bottom: 36px;
      }

      .el-form-item--default .el-form-item__content {
        align-items: normal;
        //height: 54px;
        justify-content: space-between;
      }

      .el-form-item--default,
      .el-form-item {
        width: 100%;
      }

      .el-input__wrapper {
        width: 100%;
        height: 44px;
        padding: 0 11px 0 0;
        background: rgb(242 243 245 / 100%);
        box-shadow: none;
      }

      .el-input__inner {
        //padding: 12px 0;
        font-family: 'AlibabaPuHuiTi-2-55-Regular', serif;
        //text-indent: 2.5em;
        font-size: 15px;
        line-height: 32px;
      }

      .text-13px {
        .el-input__inner {
          font-size: 13px;
        }
      }

      .el-input .el-input__prefix-inner {
        width: 22px;
        height: 22px;
        margin-top: 10px;
        margin-left: 10px;
      }

      .submitClass {
        width: 100%;
        height: 50px;
        margin-top: 10px;
        font-size: 20px;
      }

      .el-tabs__item {
        font-size: 16px;
        line-height: 30px;
      }
    }
  }
</style>
